package testScripts;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

import libraries.Excelwrite;
import libraries.KeyWordLib;
import libraries.readData;

import org.openqa.selenium.NoSuchElementException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestDriver extends AppLogin 
{
	public static Properties CONFIG = null;
	public static Properties OBJDESC = null;
	public static readData readXLData = null;
	//public static DBConnect mdbc = null;
	
	public static String testCaseID = null, testCaseExeFlag = null;
	public static String testStep, test_step_desc, testDataID;	
	public static String keyword,object,data;	
	
	public static String  vOrderNum, vUserName, vPassword, vparcelQty, vMessage, vITN, vLP, vQuery;
	public static String vLength, vWidth, vHeight, vWeight, vManifestGroup, vContainerType;
	public static String vTravelerCarrier, vAddress, vExceptionCode, vReasonCode, vComments;
	public static String vPQInttoString;
	
	public static int xTCRows, xTCCols;	 
	public static String[][] xTCdata, xTDdata;
	public static int xTSRows, xTSCols; 
	public static String[][] xTSRes;
	public String[][] xTSData;
	public static String TCxlPath = null, TSxlPath =null, scr_pass_path = null, scr_fail_path = null, v_Tsuite_xl;
	
	@BeforeTest	
	@Parameters ({"p_testsuite_xl"})
	  
	/* 
	 * Initialize object repository and test environment parameters for the application being tested.
	 */
	
	public void initialize(String testsuitexl) throws IOException{
		FileInputStream Config = new FileInputStream (System.getProperty("user.dir")+"\\src\\config\\testParameters.properties");
		CONFIG = new Properties();
		CONFIG.load(Config);

		FileInputStream objDesc = new FileInputStream (System.getProperty("user.dir")+"\\src\\config\\ObjectRepository.properties");
		OBJDESC = new Properties();
		OBJDESC.load(objDesc);
		v_Tsuite_xl = testsuitexl;
		System.out.println(v_Tsuite_xl);
	    }
	
	
	@Test

	/* 
	 * Runs the test cases and test steps for each of test case mentioned in the test controller spreadsheet.
	 */
	public void AppTest() throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		
		System.out.println("--------------"+"Test Suite Started"+"----------------");
		
		String vTS_res = "Pass", vTS_error = null, vTS_note = null ;
		String vTC_res;
		String vT_flag;
	//	String vT_Note = null;
		TCxlPath = CONFIG.getProperty("test_Case_Result_Path");
		TSxlPath = CONFIG.getProperty("test_Step_Result_Path");	
		scr_pass_path = CONFIG.getProperty("screen_Shot_Pass_Path");
		scr_fail_path = CONFIG.getProperty("screen_Shot_Fail_Path");
		
		readXLData = new readData(System.getProperty("user.dir")+v_Tsuite_xl);
  /* Read data from test controller spreadsheets, TestCases and TestData */
		xTCdata = readXLData.xlRead("TestCases");
		xTDdata = readXLData.xlRead("TestData");
		xTCdata[0][2] = "Status";
				
  /* This loop reads through test cases in Test cases Sheet and executes if the flag is set to Y */
	    for (int i = 1; i<(xTCdata.length); i++){
			testCaseExeFlag = xTCdata[i][0]; 
			testCaseID = xTCdata[i][1];
			  if (testCaseExeFlag.equals("Y")){
				  System.out.println("*--------------"+ testCaseID +" Flag is set Y"+"------------------------*");
				  vTC_res = "Skipped";
  /* Read test data for the test case being executed*/
				  for (int td = 1; td<xTDdata.length; td++){
					  if (xTDdata[td][0].equals("Y")){             /* Checking if the execute flag is Y for the data row */
						   if (xTDdata[td][1].equals(testCaseID)){ /*Read the data only if flag is Y and test case id matches with current data row */
							System.out.println("------------------------------------------");
							vTC_res = "Pass";
							testDataID     = xTDdata[td][2];
							System.out.println("Reading data from "+testDataID);
							vITN           = xTDdata[td][3];
							vOrderNum      = xTDdata[td][4];
							vMessage       = xTDdata[td][5]; 
							vLength        = xTDdata[td][6]; 							
							vWidth         = xTDdata[td][7]; 
							vHeight        = xTDdata[td][8];  
							vWeight        = xTDdata[td][9];
							vparcelQty     = xTDdata[td][10];						
							vPQInttoString = String.valueOf(Double.valueOf(vparcelQty).intValue());
							vLP            = xTDdata[td][11];
							vManifestGroup = xTDdata[td][12];
							vContainerType = xTDdata[td][13];
							vQuery         = xTDdata[td][14];
							vTravelerCarrier= xTDdata[td][15];
							vAddress       = xTDdata[td][16];
							vExceptionCode = xTDdata[td][17];
							vReasonCode    = xTDdata[td][18];
							vComments      = xTDdata[td][19];
							
							xTSRows = readXLData.getRowCount(testCaseID);
							xTSCols = readXLData.getColCount(testCaseID);
							xTSRes = new String[xTSRows][xTSCols+1];
	/* Read & execute test steps for the test case being executed*/							
					 for(int j = 1; j<xTSRows; j++){
								System.out.println("-------------------------------------");
								xTSData        = readXLData.xlRead(testCaseID);
								testStep       = xTSData[j][0];
								keyword        = xTSData[j][1];
								test_step_desc = xTSData[j][2];
								object         = xTSData[j][3];
								vTS_note       = null;

								if(!(xTSData[j][4].equals("NA"))){
									data = xTSData[j][4];
									System.out.print("Data Input is "+ data+ " ;");
									getIP();
								}
								System.out.print("Object Name is " + object+ " ;");
								System.out.print(" Keyword is " + keyword+ " ;");
								System.out.println();
								System.out.println("Running Test step "+testStep+" for "+ testCaseID);
							   try {
									Method method = KeyWordLib.class.getMethod(keyword);
									vT_flag = (String) method.invoke(method);
									
									  if (vT_flag.contains("Fail")){
										vTS_res   = "Fail";
										vTS_error = vT_flag;
										vTC_res   = "Fail";
									    } 
									 
									  else if (!vT_flag.contains("Pass")){
										     vTS_note   = vT_flag;
											 } 
								    } 
								catch (NoSuchElementException e) {
									vTS_res   = "Fail";
									vTS_error = "Element missing " + e;
									vTC_res   = "Fail";
								}
								
								
/* Create result for  test steps being executed*/								   
								xTSRes[0][0] = "Test Case ID";
								xTSRes[0][1] = "Test Step ID";
								xTSRes[0][2] = "Description";	
								xTSRes[0][3] = "Result";								
								xTSRes[0][4] = "Error";
								xTSRes[0][5] = "Notes";
								xTSRes[j][0] = testCaseID;
								xTSRes[j][1] = testStep;
								xTSRes[j][2] = test_step_desc;	
								xTSRes[j][3] = vTS_res;
								xTSRes[j][3] = vTS_res;
								xTSRes[j][4] = vTS_error;
								xTSRes[j][5] = vTS_note;
								
/* Create screenshots for  test steps being executed*/								
								/*File scrFile = ((TakesScreenshot)webdriver).getScreenshotAs(OutputType.FILE);
								if (vTS_res.equals("Fail")){								
									FileUtils.copyFile(scrFile, new File(scr_fail_path+testCaseID+"_"+testDataID+"_"+testStep+"_Fail"+".jpg"));
								} 
								else {FileUtils.copyFile(scrFile, new File(scr_pass_path+testCaseID+"_"+testDataID+"_"+testStep+"_Pass"+".jpg"));}
*/
/* Reset test result and error message after each test step loop */
								vTS_res = "Pass";
								vTS_error = null;
							}// J loop
						
					System.out.println("*------End of Test Steps for "+testCaseID+" Test case-----*");
/* Write test result detail report after each test step loop */
					         try {
								Excelwrite.xlwrite(TSxlPath,testCaseID+"_"+testDataID, xTSRes);
							    } catch (Exception e) {
								  e.printStackTrace();
							      }

						} // td if test case id matches then read the data
						else
						{
							System.out.println("Skipping " + readXLData.getStringCellValue("TestData", td, 2)+" because TCID doesn't match");
						}	
					} // td if test case Ex flag = Y then read the data		
					  else
						{
							System.out.println("Skipping " + readXLData.getStringCellValue("TestData", td, 2)+" because Flag is set to N");
						} 
					  
				} // Read data loop	td
				
				xTCdata[i][2] = vTC_res;
				System.out.println("Test case completed " +xTCdata[i][2]);
			} // close of condition if execute = Y inside the loop i
			
			   else   // if Test case execute = N
			   {
				System.out.println("Skipping " + testCaseID);
				xTCdata[i][2] = "Skipped";
			   }
              
	    } //-- i loop
			 
// Write Test summary excel report			
		       try {
			       Excelwrite.xlwrite(TCxlPath,"Test_Result_Summary", xTCdata);

		           } catch (Exception e) 
		             {
			         e.printStackTrace();
		             }
		System.out.println("Main Test Suite End");
		System.out.println("------------------------------------------------------");
											
			 
				/*try {
					KeyWordLib.DB_ResultSet();
				} catch (SQLException | ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					*/	    				
				
	}

	public static void getIP(){

		if (data.equals("OrderNumber")){
			data = vOrderNum;
		}
		if (data.equals("ITN")){
			data = vITN;
		}
		if (data.equals("ParcelQuantity")){
			data = vPQInttoString;
		}
		if (data.equals("Message")){
			data = vMessage;
		}
		if (data.equals("LP")){
			data = vLP;
		}
		if (data.equals("ManifestGroup")){
			data = vManifestGroup;
		}
		if (data.equals("ContainerType")){
			data = vContainerType;
		}
		if (data.equals("Query")){
			data = vQuery;
		}
		if (data.equals("TravelerCarrier")){
			data = vTravelerCarrier;
		}
		if (data.equals("Address")){
			data = vAddress;
		}
		if (data.equals("ExceptionCode")){
			data = vExceptionCode;
		}
		if (data.equals("ReasonCode")){
			data = vReasonCode;
		}
		if (data.equals("Comments")){
			data = vComments;
		}
	}

}
